package com.bw.polling.view

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.constants.RoutePath
import com.bw.common.adapter.ImgAdapter
import com.bw.common.view.BaseMvvmActivity
import com.bw.polling.R
import com.bw.polling.databinding.ActivityAddPollingBinding
import com.bw.polling.databinding.ActivityPollingBinding
import com.bw.polling.entity.PollingEntity
import com.bw.polling.net.PollingViewModel
/**
 *  智慧园区-07 -新增点位 -v1.1-张梦停
 *  2025/05/13
 */
@Route(path = RoutePath.PATH_ADD_POLLING)
class AddPollingActivity :  BaseMvvmActivity<ActivityAddPollingBinding,PollingViewModel>() {
    lateinit var imgAdapter: ImgAdapter
    private val imagePaths = mutableListOf<String>()
    private var MAX_IMAGE : Int = 9
    override fun initView() {
        binding.topBar.ivBack.setOnClickListener { finish() }
        binding.topBar.ivMore.visibility = View.VISIBLE
        binding.topBar.tvTitle.text = "新增点位"
        imgAdapter = ImgAdapter()
        updateAddButtonVisibilty()
        imgAdapter.setOnItemClickListener { adapter, view, position ->
            if (position == adapter.data.size -1 && adapter.data[position] == "+"){
                selectPicture()
            }else{
                showImagePreview(position)
            }
        }
        binding.re.adapter = imgAdapter
        binding.re.layoutManager = GridLayoutManager(this,3)
        // 图片 长按 删除
        imgAdapter.setOnItemLongClickListener { adapter, view, position ->
            if (position < adapter.data.size && adapter.data[position] != "+"){
                AlertDialog.Builder(this)
                    .setTitle("删除图片")
                    .setMessage("确定是否删除图片吗？")
                    .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                        removeImage(position)
                    })
                    .setNegativeButton("取消",null)
                    .show()
                true
            }else{
                false // 返回false 表示事件未处理
            }
        }
    }

    // 使用ActivityResultContracts启动图片选择
    private val selectPictureLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data = result.data
            if (data != null) {
                // 处理选择的图片
                val selectedImageUri = data.data
                if (selectedImageUri != null) {
                    addImage(selectedImageUri)
                }
            }
        }
    }
    private fun selectPicture(){
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        selectPictureLauncher.launch(intent)
    }

    private fun addImage(imageUri : Uri){
        val imagePAth = imageUri.toString()
        if (imagePaths.isNotEmpty() && imagePaths.last()== "+"){
            imagePaths.removeAt(imagePaths.size -1)
        }
        imagePaths.add(imagePAth)
        if (imagePaths.size < MAX_IMAGE){
            imagePaths.add("+")
        }
        imgAdapter.setList(imagePaths)
    }
    private fun removeImage(position: Int){
        val hasADdButton = imagePaths.contains("+")
        imagePaths.removeAt(position)
        if (!hasADdButton && imagePaths.contains("+")){
            imagePaths.add("+")
        }
        imgAdapter.setList(imagePaths)
    }
    private fun updateAddButtonVisibilty() {
        if (imagePaths.isEmpty() || (imagePaths.last() !="+" && imagePaths.size<MAX_IMAGE)){
            if (imagePaths.isNotEmpty() && imagePaths.size >= MAX_IMAGE){
                if (imagePaths.last() == "+"){
                    imagePaths.removeAt(imagePaths.size -1)
                }
            }else{
                imagePaths.add("+")
            }
            imgAdapter.setList(imagePaths)
        }
    }
    private fun showImagePreview(position :Int){
        ToastUtils.showLong("预览图片${imagePaths[position]}")
    }

    override fun initData() {
        binding.bu.setOnClickListener {
            vm.addPolling(
                PollingEntity(
                    0,
                    "1,3", binding.et3.text.toString(),
                    "",binding.et4.text.toString(),
                    "点位5",binding.et5.text.toString()
                )
            )
        }
        vm.addPollingSuccess.observe(this){
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

}